package com.system.vote.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.vote.admin.entity.SysMemo;
import com.system.vote.admin.exception.BusinessException;
import com.system.vote.admin.security.JwtUtil;
import com.system.vote.admin.service.SysMemoService;
import com.system.vote.common.utils.StringUtils;
import com.system.vote.core.customBean.PageBean;
import com.system.vote.core.http.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/memo")
@Api(tags = "PC后台备忘录")
public class SysMemoController {

    @Autowired
    private SysMemoService sysMemoService;

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:memo:list')")
    @ApiOperation(value = "备忘录列表")
    public Result list(HttpServletRequest request, @RequestBody PageBean pageBean) {
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        String uid = claims.getId();
        String query = pageBean.getQuery();
        String isFinish=pageBean.getIsFinish();
        Page<SysMemo> pageResult = sysMemoService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new LambdaQueryWrapper<SysMemo>()
                        .eq(SysMemo::getUid,uid)
                        .and(StringUtils.isNotEmpty(isFinish),e->e.eq( SysMemo::getIsFinish,isFinish))
                        .like(StringUtils.isNotEmpty(query), SysMemo::getTitle, query.trim())
                        .ne(SysMemo::getIsDelete, 1)
                        .orderByDesc(SysMemo::getUpdateTime));
        List<SysMemo> sysMemoList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", sysMemoList);
        resultMap.put("total", pageResult.getTotal());

        return Result.success(resultMap);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('system:memo:add')")
    @ApiOperation(value = "新增备忘录")
    public Result addMemo(HttpServletRequest request, @RequestBody SysMemo sysMemo) {
        if (sysMemo.getId() < 0) {
            String token = request.getHeader("token");
            Claims claims = JwtUtil.parseJWT(token);
            String uid = claims.getId();
            sysMemo.setCreateTime(new Date());
            sysMemo.setUpdateTime(new Date());
            sysMemo.setIsFinish(0);
            sysMemo.setIsDelete(0);
            sysMemo.setUid(Long.valueOf(uid));
            sysMemoService.save(sysMemo);
        } else {
            throw new BusinessException("参数错误");
        }
        return Result.success("新增备忘录成功");
    }

    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('system:memo:edit')")
    @ApiOperation(value = "编辑备忘录")
    public Result editMemo(@RequestBody SysMemo sysMemo) {
        if (sysMemo.getId() > 0) {
            sysMemo.setUpdateTime(new Date());
            sysMemoService.updateById(sysMemo);
        } else {
            throw new BusinessException("参数错误");
        }
        return Result.success("编辑备忘录成功");
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:memo:query')")
    @ApiOperation(value = "查询备忘录")
    public Result findById(@PathVariable Integer id) {
        SysMemo sysMemo = null;
        if (id > 0) {
            sysMemo = sysMemoService.getById(id);
        } else {
            throw new BusinessException("参数错误");
        }
        return Result.success(sysMemo);
    }

    @PostMapping("/checkTitle")
    @PreAuthorize("hasAuthority('system:memo:query')")
    @ApiOperation(value = "检查标题是否为空")
    public Result checkUserName(@RequestBody SysMemo sysMemo) {
        if (sysMemoService.getByTitle(sysMemo.getTitle()) == null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:memo:delete')")
    @ApiOperation(value = "批量删除")
    public Result delete(@RequestBody List<SysMemo> sysMemoList) {
        sysMemoList.forEach(t -> {
            t.setIsDelete(1);
        });
        sysMemoService.saveOrUpdateBatch(sysMemoList);
        String msg = sysMemoList.size() == 1 ? "删除成功" : "批量删除成功";
        return Result.success(msg);
    }

    @PostMapping("/updateMemoStatus")
    @PreAuthorize("hasAuthority('system:memo:edit')")
    @ApiOperation(value = "更新备忘录状态")
    public Result updateMemoStatus(@RequestBody SysMemo sysMemo) {
        SysMemo currentSysMemo = sysMemoService.getById(sysMemo.getId());
        currentSysMemo.setUpdateTime(new Date());
        currentSysMemo.setStatus(sysMemo.getStatus());
        sysMemoService.updateById(currentSysMemo);
        return Result.success("更新备忘录状态成功");
    }
    @PostMapping("/updateMemoFinish")
    @PreAuthorize("hasAuthority('system:memo:edit')")
    @ApiOperation(value = "更新备忘录完成情况")
    public Result updateMemoFinish(@RequestBody SysMemo sysMemo) {
        SysMemo currentSysMemo = sysMemoService.getById(sysMemo.getId());
        currentSysMemo.setIsFinish(sysMemo.getIsFinish());
        sysMemoService.updateById(currentSysMemo);
        return Result.success("更新备忘录完成情况成功");
    }
}

